from package.connector.sql_db import db
from model.model import Dashboard, Panelib, PanelibData
from common.analyzer_common.panel import PanelSearch
from package.fastapi.job import scheduler_job


class DashboardView(Dashboard):
    @classmethod
    def _get_dashboard_panelibs(cls, session, panelib_ids):
        """获取 dashboard下panelib"""
        return Panelib.get_items(session=session, filter_=[Panelib.id.in_(panelib_ids)]).all()
    
    @classmethod
    def get_dashboard_panel(cls, session, filter_):
        item = cls.get_item(session=session, filter_=filter_)
        panelib_ids = [layout['panel_id'] for layout in item.layout if layout['category'] == 'panelib']  # dashboard 下所有图表 可能包含其他图例如关系视图等
        panels = cls._get_dashboard_panelibs(session, panelib_ids)
        return panels


class PanelibView(Panelib):
    """图表"""
    Prefix = 'analyzer:panelib:cron:'

    @classmethod
    def execute(cls, id, search, configure):
        data = PanelSearch.visualize_data(search=search, configure=configure)
        with db.SessionLocal() as session:
            cls.update_item(session=session, filter_=[cls.id == id], update={'cache': data})

    @classmethod
    def update_panelib(cls, session, filter_, update):
        item = cls.update_item(session=session, filter_=filter_, update=update)
        scheduler_job.add_job(job_id=f'{cls.Prefix}{item.id}', func=cls.execute, cron=item.cron, 
                              kwargs={'id': item.id, 'search': item.search, 'configure': item.configure})
        return item

    @classmethod
    def delete_panelibs(cls, session, filter_):
        item = cls.get_items(session=session, filter_=filter_)
        scheduler_job.delete_job(job_id=f'{cls.Prefix}{item.id}')
        return cls.create_items(session=session, filter_=filter_)
    
    @classmethod
    def create_panelib(cls, session, body):
        item = cls.create_item(session, body=body)
        scheduler_job.add_job(job_id=f'{cls.Prefix}{item.id}', func=cls.execute, cron=item.cron, 
                              kwargs={'id': item.id, 'search': item.search, 'configure': item.configure})
        return item

    @classmethod
    def get_item_search(cls, search, configure):
        return PanelSearch.visualize_data(search, configure)
    
    @classmethod
    def get_item_data(cls, session, id):
        item_data = session.query(PanelibData).filter(PanelibData.id == id).first()
        return item_data or {}

    @classmethod
    def put_item_data(cls, session, id, data):
        item = PanelibData.get_item(session, filter_=[PanelibData.id == id], error=False)
        if not item:
            item = PanelibData.create_item(session, body={'id': id, **data})
            return item
        item = PanelibData.update_item(session, filter_=[PanelibData.id == id], update=data)
        return item
